# -*- coding: utf-8 -*-
import datetime
import math
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urljoin, json, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class FujianZfxxgkPolicy(BaseTaxPolicySpider):
    name = 'fujian_longyan_siteId_policy'

    province = '福建省'
    city = '龙岩市'
    # county = ''
    park = ''
    page_size = int(26 * 1.5)

    def __init__(self, get_next=False, **kwargs):
        super().__init__(**kwargs)
        print(get_next)
        self.get_next = get_next

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                "DOWNLOAD_TIMEOUT": 200,
                "CONCURRENT_REQUESTS": 5,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 407, 500, 200, 202, 502, 429, 521],
                "DOWNLOAD_DELAY": 5,
                # "DOWNLOADER_MIDDLEWARES": {
                #     "components.middlewares.downloadmiddlewares.public.useragent_random.RandomUserAgentMiddleware": None,
                #     "components.middlewares.downloadmiddlewares.public.company_ip_by_api.CompanyIpByApiMiddleware": None,
                #     "components.middlewares.downloadmiddlewares.public.error_collector.ErrorCollectorMiddleware": None,
                #     # **downloader_middlewares
                # }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ["龙岩市人民政府", "", "https://www.longyan.gov.cn/gk/zcwjk/"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self._parser_dataproxy_html,
                                 meta={"item": item})

    def _parser_dataproxy_html(self, response):
        meta = response.meta

        siteId = response.xpath("//*[@name='siteId']/@value").get()

        params = {
            "siteId": siteId,
            "requestType": "getInfo",
            "page": "1",
            "sourceType": "SSP_QSZCWJK",
            "apiName": "SSP_QSZCWJK",
            "sortFiled": "-docreltime",
            "themeType": "-1",
            "isCollapse": "N",
            "fullKey": "Y",
            "isChange": "1",
            "datas": "10"
        }
        url = response.urljoin('/ssp/search/api/apiSearch') + '?'
        temp_url = url + urllib.parse.urlencode(params)
        meta.update({
            "params": params,
            "siteId": siteId,
            "url": url
        })
        print(params)
        yield self.Request(
            temp_url,
            callback=self.parse_list,
            dont_filter=True,
            meta=meta
        )

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        meta = response.meta
        siteId = meta['siteId']
        url_list = response.json()['datas']
        for elem in url_list:
            item = Item()
            item['source_url'] = elem['chnldocurl']
            # item['source_url'] = response.urljoin(f'/cms/infopublic/publicInfo.shtml?id={elem["id"]}&siteId={siteId}')
            item['publish_date'] = elem['pubdate'].split(" ")[0].replace('.', '-')
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        page = meta.get('page', 1)
        if page > 800 or meta.get('is_next') is False:
            return
        page += 1
        total_page = int(response.json()['page']['pagecount'])
        # total_page = math.ceil(total_count / 50)
        print(meta['params'], page, "total_page", total_page)
        for page in list(range(2, total_page + 1))[:800]:
            meta['is_next'] = False
            params = meta['params']
            url = meta['url']
            params['page'] = page
            meta['page'] = page
            temp_url = url + urllib.parse.urlencode(params)
            self.logger.info(f"{total_page} 开始爬取 第 {page} 页 data: {params['siteId']}")
            yield self.Request(
                temp_url,
                meta=meta,
                callback=self.parse_list,
                dont_filter=True
            )

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = item['publish_date'] or response.xpath(
            """string(//meta[@name='PubDate']/@content)""").get() or response.xpath(
            "//*[@class='fbrq']/text()").get()
        if item['publish_date']:
            item['publish_date'] = item['publish_date'].split(" ")[0]
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl fujian_longyan_siteId_policy -a get_next=0".split())
